package com.viki.test.testvisitinternet;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.net.http.SslError;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

public class SimulateWeiboActivity extends Activity {
	private final String TAG = "OauthorWebActivity";
	// 1. 引导需要授权的用户到如下地址
	private final String URL = "https://api.weibo.com/oauth2/authorize?client_id=1615553842&response_type=code&redirect_uri=http://mse.360.cn";
	// 2. 如果用户同意授权,页面跳转至 YOUR_REGISTERED_REDIRECT_URI/?code=CODE 
	private String CODE = new String();
	// 3. 换取Access Token 
	public static String ACCESS_TOKEN = "https://api.weibo.com/oauth2/access_token?client_id=1615553842&client_secret=a95e7af7c4bdbbd8b695196555b49652&grant_type=authorization_code&redirect_uri=http://mse.360.cn&code=";	
	// 请求地址
	private final String REQUEST_URL = "https://api.weibo.com/2/statuses/public_timeline.json";
	private Button mVisit;
	private WebView mWebView;
	private TextView mResult;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simulateweibo);
        mVisit = (Button) findViewById(R.id.visit);
        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.setWebViewClient(mWebClient);
        mResult = (TextView) findViewById(R.id.result);
        mVisit.setOnClickListener(mVisitClickListener);
    }
	private OnClickListener mVisitClickListener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// 引导进入授权页面
			mWebView.loadUrl(URL);
		}
	};
	private WebViewClient mWebClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.d(TAG,"url =="+url);  
                // 点击登陆后截取跳转地址中的code参数
                String code = getRequestCode(url);
                if(null == code)
                { 
                	Log.d(TAG,"Fail to get request code");
                	return false;
                }
                CODE = code;               
                String newUrl = ACCESS_TOKEN + CODE;
                Log.d(TAG,"access_token url is "+ACCESS_TOKEN);
                
                // 用code换取access_token
                String result = HttpsConnection.sendPostURL(newUrl, null, null);
                Log.d(TAG,"access_token result " + result);
                
                // 解析请求地址返回的内容，获取access_token
                try {
					JSONObject jo = new JSONObject(result);
					ACCESS_TOKEN = jo.getString("access_token");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}              
                mResult.setText(result);
                mVisit.setText("publicTimeline");
                mVisit.setOnClickListener(mPublicClickListener);
                mWebView.setVisibility(View.GONE);

                return true;
        }
        private OnClickListener mPublicClickListener = new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// 发起请求，在Header中已设置access_token值，见HttpsConnection
				String result = HttpsConnection.sendGetURL(REQUEST_URL,null,null);
				mResult.setText(result);
				ViewGroup vg = (ViewGroup) mResult.getParent();
				vg.removeView(mResult);
				ScrollView scrollView = new ScrollView(SimulateWeiboActivity.this);
				scrollView.addView(mResult, new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
				vg.addView(scrollView);
			}
		};
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){  
                handler.proceed();
        }
        private String getRequestCode(String url){
        	String params=url.substring(url.lastIndexOf("?")+1);
           	Map<String ,String> paramsMap= new HashMap<String, String>();
           	for(String s:params.split("&")){
           			String[] t=s.split("=");
           			paramsMap.put(t[0],t[1]);
           	}
           	return paramsMap.get("code");
        }
     };
}
